package com.wujilee.caffeine.controller;


import com.github.benmanes.caffeine.cache.Cache;
import com.wujilee.caffeine.entity.CaffeineVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/caffeine")
public class CaffeineController {
    @Resource
    private Cache<Object, Object> caffeineCache;

    @PostMapping()
    public void put(@RequestBody CaffeineVO<String> caffeineVO) {
        caffeineCache.put(caffeineVO.getKey(), caffeineVO.getValue());
    }

    @GetMapping()
    public String get(String key) {
        return (String) caffeineCache.get(key, t -> "000");

    }

    @GetMapping("/estimatedSize")
    public CaffeineVO estimatedSize(String key) {
        CaffeineVO<String> vo = new CaffeineVO<>();
        vo.setHitCount(caffeineCache.stats().hitCount());
        vo.setMissCount(caffeineCache.stats().missCount());
        vo.setHitRate(caffeineCache.stats().hitRate());
        vo.setValue((String) caffeineCache.get(key, t -> "000"));
        return vo;
    }
}
